//index.js
//获取应用实例
import encode from '../../../utils/base64.js';
import request from '../../../utils/config.js';
import util from '../../../utils/util.js';
let WXBizDataCrypt = require('../../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({
  data: {
    windowHeight: wx.getSystemInfoSync().windowHeight - 167,
    statusHeight: wx.getSystemInfoSync().windowHeight - 107,
    searchCheckHieght: wx.getSystemInfoSync().windowHeight - 100,
    pageNum: 1,
    totalPage: "",
    pageStatusNum: 1,
    totalStatusPage: "",
    defaultName: "",
    defaultImg: "",
    statusDefaultImg: "../../../img/man.png",
    defaultDepart: "lawsuitInvest",//执行("enforce"), 诉讼("lawsuit"),市场部("lawsuitInvest")
    menuTab: "task",//任务列表("task"),//关注("collect"),客户列表("client"),律师协助("lawyerHelp")
    loginUserInfo: "",
    taskNum: "0",
    collectNum: "0",
    clientNum: "0",
    searchValue: "",
    serachFlag: "",
    caseList: [],
    delBtnWidth: 180,//删除按钮宽度单位（rpx）
    showCaseList: true,
    showStatusList: false,
    showShareDocList: false,
    folderList: [],
    stateList: [],
    departmentList: [],
    level: 0,//目录级别
    categoryIdList: [],//返回上级目录Id
    isFromOpenDoc: false,//打开文档返回后页面不要刷新
    isGetNextPage: false,
    isHidden: false,
    show_client: false,//控制搜索按钮的显示
    searchNum: 0,//搜索结果数量
    toDoNumSlt: true,//控制待办列表是否高亮
    dynamicStateSlt: false,//控制客户列表是否高亮
    searchNumStatus: false,//搜索结果显示与隐藏
  },


  onPullDownRefresh: function () {
    this.setData({
      searchValue: "",
      serachFlag: ""
    });
    this.getStatusNum(this.data.defaultDepart);
    setTimeout(function () {
      wx.showToast({
        title: '加载成功',
        icon: 'success',
        duration: 1000
      })
      wx.stopPullDownRefresh();
    }, 1000);
    console.log("执行了一次下拉刷新")
  },


  onLoad: function (options) {
    console.log("options=", options)
    let flagName = options.flagName;
    let departmentList = wx.getStorageSync("departmentList");
    console.log("departmentList===", departmentList)
    this.setData({
      defaultDepart: flagName,
      departmentList: JSON.parse(departmentList),
      ROLE_LawyerAssistApply: app.globalData.loginUserInfo.roles.includes('ROLE_LawyerAssistApply'),
    });
    this.initEleWidth();
  },

  onShow: function () {
    if (app.globalData.listRefresh.SuSong&&!app.globalData.listRefresh.SuSong.refresh){
      this.getListItem()
      return
    }
    if (this.data.isFromOpenDoc) {
      this.setData({ isFromOpenDoc: false })
    } else {
      app.globalData.is_clientPro_grade_change = false
      let loginUserInfo = app.globalData.loginUserInfo;
      this.setData({
        loginUserInfo: loginUserInfo,
        defaultName: app.globalData.userInfo.nickName,
        defaultImg: app.globalData.userInfo.avatarUrl
      })
      //开始校验看token值
      this.checkToken();
    }
  },
  getListItem(){
    let typeTab = this.data.menuTab;
    if (!app.globalData.listRefresh.SuSong.custId) {
      return;
    }
    if (typeTab == "task") {
      let bodyInfo = {
        type: this.data.defaultDepart,
        operId: app.globalData.operId,
        pageNum: '1',
        pageSize: '10',
        creditorName: this.data.searchValue || "",
        custId:app.globalData.listRefresh.SuSong.custId
      }

      let _this = this;
      console.log(bodyInfo)
      request.requestGetMis_api("flyWorkPlace/cases", wx.getStorageSync("token"), bodyInfo, (res) => {
        let taskList = JSON.parse(res.data.body);
        console.log("获取任务列表成功custId=custId", taskList)
        if (taskList.length > 0) {
          taskList[0].txtStyle = "";
          let grade = taskList[0].grade
          taskList[0].img = (grade == 3) ? 'stateA.png' : (grade == 2) ? 'stateB.png' : (grade == 1) ? 'stateC.png' : 'state0.png';
          let caseList = _this.data.caseList;
          caseList[app.globalData.listRefresh.SuSong.itemIndex] = taskList[0]
          _this.setData({
            caseList: caseList,
          });
        }
      }, (res) => {
        console.log("获取任务列表失败=", res)
      });
    } else if (typeTab == "collect") {
      let bodyInfo = {
        pageNum: '1',
        pageSize: '10',
        custName: this.data.searchValue || "",
        custId: app.globalData.listRefresh.SuSong.custId
      }
      let _this = this;
      console.log(bodyInfo)
      request.requestGetMis_api("favorCusts", wx.getStorageSync("token"), bodyInfo, (res) => {
        let taskList = JSON.parse(res.data.body);
        console.log("获取收藏表成功custId=custId", taskList)
        let caseList = _this.data.caseList;
        if (taskList.length > 0) {
          taskList[0].txtStyle = "";
          taskList[0].isFavor = "Y";
          let grade = taskList[0].grade
          taskList[0].img = (grade == 3) ? 'stateA.png' : (grade == 2) ? 'stateB.png' : (grade == 1) ? 'stateC.png' : 'state0.png';
          caseList[app.globalData.listRefresh.SuSong.itemIndex] = taskList[0]
        }else{
          caseList[app.globalData.listRefresh.SuSong.itemIndex].isFavor = "N"
          _this.setData({
            searchNum: _this.data.searchNum*1-1,
          });
        }
        _this.setData({
          caseList: caseList,
        });
      }, (res) => {
        console.log("获取收藏列表失败=", res)
      });
    } else if (typeTab == "client") {
      let bodyInfo = {
        type: this.data.defaultDepart,
        operId: app.globalData.operId,
        pageNum: '1',
        pageSize: '10',
        creditorName: this.data.searchValue || "",
        custId: app.globalData.listRefresh.SuSong.custId
      }

      let _this = this;
      console.log(bodyInfo)
      request.requestGetMis_api("flyWorkPlace/customs", wx.getStorageSync("token"), bodyInfo, (res) => {
        console.log("获取客户列表成功custId=custId", JSON.parse(res.data.body))
        let taskList = JSON.parse(res.data.body);
        if (taskList.length > 0) {
          taskList[0].txtStyle = "";
          let grade = taskList[0].grade
          taskList[0].img = (grade == 3) ? 'stateA.png' : (grade == 2) ? 'stateB.png' : (grade == 1) ? 'stateC.png' : 'state0.png';
          let caseList = _this.data.caseList;
          caseList[app.globalData.listRefresh.SuSong.itemIndex] = taskList[0]
          _this.setData({
            caseList: caseList,
          });
        }
      }, (res) => {
        console.log("获取客户列表失败=", res)
      });
    }
  },
  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function(res){
      _that.setData({
        loginUserInfo: res.loginUserInfo,
      });
      let tempList = res.tempList;
      let flagName = res.flagName;
      let jurisdiction = res.jurisdiction;
      let roleQuanxian = res.roleQuanxian;
      let department = res.department;
      if (tempList.length == 0) {
          wx.showModal({
            title: '对不起',
            content: '您的权限不足',
            confirmText: "知道了",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../../index/index',
                })
              } else if (res.cancel) {

              }
            }
          })
          return;
        }

        //校验上次记住的部门权限是否还存在
        if (jurisdiction.indexOf(roleQuanxian) < 0) {
          wx.showModal({
            title: '对不起',
            content: "您的" + department + "部门权限不足,请重新登录并选择相关部门",
            confirmText: "知道了",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../../index/index',
                })
              } else if (res.cancel) {
              }
            }
          })
          return;
        }
        _that.getStatusNum(_that.data.defaultDepart);
    },function(res){
      //登录超时
        wx.showModal({
          title: '登录超时',
          content: '点击确定重新登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
    });
  },

  //获取动态数量
  getStatusNum: function (type, flag) {
    let bodyInfo = {
      type: type
    }
    let _this = this;
    request.requestGetMis_api("flyWorkPlace", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("动态数量成功=", res)
      let bodyList = JSON.parse(res.data.body);
      let taskNum = "0";
      let collectNum = "0";
      let clientNum = '0';
      bodyList.forEach(function (e) {
        if (e.trips == '任务列表') {
          taskNum = e.number + "";
        } else if (e.trips == '我的收藏') {
          collectNum = e.number + "";
        } else if (e.trips == "客户列表") {
          clientNum = e.number + "";
        }
      });
      _this.setData({
        taskNum: taskNum,
        collectNum: collectNum,
        clientNum: clientNum
      });

      //任务列表("task"),//关注("collect"),客户列表("client")
      let typeTab = _this.data.menuTab;
      if (flag != "gz") {
        if (!this.data.serachFlag) {
          if (typeTab == "task") {
            _this.getTaskCaseList(type, 1);
            _this.setData({
              dynamicStateSlt: false,
              toDoNumSlt: true,
            });
          } else if (typeTab == "collect") {
            this.getCollectCaseList(type, 1);
            _this.setData({
              dynamicStateSlt: false,
              toDoNumSlt: false,
            });
          } else if (typeTab == "client") {
            this.getClientCaseList(type, 1);
            _this.setData({
              dynamicStateSlt: true,
              toDoNumSlt: false,
            });
          } else if (typeTab == "lawyerHelp") {
            this.getCounselCaseList(type, 1)
          } else if (typeTab == "ShareDoc") {
            _this.getCategoryList(0, '', 1);
          }
        }
      }
    }, (res) => {
      console.log("动态数量失败=", res)
    });
  },


  //获取搜索查询值
  getSearchValue: function (e) {
    var searchValue = e.detail.value;
    this.setData({
      searchValue: searchValue
    });
  },
  delSearchValue: function() {
    this.setData({
      searchValue: ''
    });
  },

  //开始调用查询接口
  startSearchFun: function () {
    if (this.data.menuTab != 'lawyerHelp'&&!this.data.isHidden) {
      this.setData({ isHidden: true, searchNumStatus:false })
      return
    }
    let value = this.data.searchValue;
    this.setData({
      serachFlag: 1,
      caseList: new Array(),
      searchNumStatus: true
    });
    if (this.data.menuTab == 'task') {
      if (this.data.isHidden) {
        this.setData({
          isHidden: false,
        })
        this.getTaskCaseList(this.data.defaultDepart, 1);
      } else {
        this.setData({ isHidden: true, })
      }
    } else if (this.data.menuTab == 'collect') {
      if (this.data.isHidden) {
        this.setData({
          isHidden: false,
        })
        this.getCollectCaseList(this.data.defaultDepart, 1);
      } else {
        this.setData({ isHidden: true, })
      }
    } else if (this.data.menuTab == 'client') {
      if (this.data.isHidden) {
        this.setData({
          isHidden: false,
        })
        this.getClientCaseList(this.data.defaultDepart, 1);
      } else {
        this.setData({ isHidden: true, })
      }
    } else if (this.data.menuTab == 'lawyerHelp') {
      this.getCounselCaseList(this.data.defaultDepart, 1);
    }
  },

  //选择搜索标签
  searchSign: function (e) {
    this.setData({
      isHidden: false,
      toDoNumSlt: false,
      dynamicStateSlt: false,
    });
    if (e.currentTarget.dataset.sign == 'collect') {
      this.setData({
        menuTab: 'collect',
        searchValue: ""
      })
      this.getCollectCaseList(this.data.defaultDepart, 1);
    } else if (e.currentTarget.dataset.sign == 'deal') {
      this.setData({
        menuTab: 'task',
        toDoNumSlt: true,
        searchNumStatus: true,//搜索结果显示与隐藏
        searchValue: ""
      })
      this.getTaskCaseList(this.data.defaultDepart, 1);
    } else if (e.currentTarget.dataset.sign == 'client') {
      this.setData({
        menuTab: 'client',
        dynamicStateSlt: true,
        searchNumStatus: true,//搜索结果显示与隐藏
        searchValue: ""
      })
      this.getClientCaseList(this.data.defaultDepart, 1);
    }
  },

  //点击搜索框事件
  isHiddenChange: function () {
    if (this.data.menuTab == 'task' || this.data.menuTab == 'collect' || this.data.menuTab == 'client') {
      this.setData({ isHidden: true, searchNumStatus: false })
    }
  },
  cancelSearch: function () {
    this.setData({ isHidden: false, searchNumStatus: true })
  },
  //获取任务列表数据
  getTaskCaseList: function (typeFlag, pageNum) {
    if (pageNum == 1) {
      this.setData({
        searchNum: 0,
        caseList: new Array()
      });
    }

    let bodyInfo = {
      type: typeFlag,
      operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10',
      creditorName: this.data.searchValue || ""
    }

    let _this = this;
    request.requestGetMis_api("flyWorkPlace/cases", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("获取任务列表成功=", res)
      let taskList = JSON.parse(res.data.body);
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (taskList.length > 0) {
        let tempList = _this.data.caseList;
        taskList.forEach(function (e) {
          e.txtStyle = "";
          e.img = (e.grade == 3) ? 'stateA.png' : (e.grade == 2) ? 'stateB.png' : (e.grade == 1) ? 'stateC.png' : 'state0.png';
        });
        for (var i = 0; i < taskList.length; i++) {
          tempList.push(taskList[i]);
        }
        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          searchNum: res.data.totalNum,
          totalPage: res.data.totalPage,
        });
      }
    }, (res) => {
      console.log("获取任务列表失败=", res)
    });
  },

  //获取收藏列表
  getCollectCaseList: function (type, pageNum) {
    if (pageNum == 1) {
      this.setData({
        caseList: new Array(),
        searchNum: 0
      });
    }
    let bodyInfo = {
      // type: type,
      // operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10',
      custName: this.data.searchValue || ""
    }

    let _this = this;
    console.log(bodyInfo)
    request.requestGetMis_api("favorCusts", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("获取收藏表成功=", res)
      let taskList = JSON.parse(res.data.body);
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (taskList.length > 0) {
        let tempList = _this.data.caseList;
        taskList.forEach(function (e) {
          e.txtStyle = "";
          e.img = e.grade == 3 ? 'stateA.png' : e.grade == 2 ? 'stateB.png' : (e.grade == 1) ? 'stateC.png' : 'state0.png';
          e.isFavor = "Y"
        });
        for (var i = 0; i < taskList.length; i++) {
          tempList.push(taskList[i]);
        }
        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          totalPage: res.data.totalPage,
          searchNumStatus: true,
          searchNum: res.data.totalNum,
        });
      }
    }, (res) => {
      console.log("获取收藏列表失败=", res)
    });
  },

  //获取客户列表
  getClientCaseList: function (type, pageNum, flag) {
    if (pageNum == 1) {
      this.setData({
        searchNum: 0,
        caseList: new Array()
      });
    }
    // this.setData({
    //   searchNum: 0
    // });
    let bodyInfo = {
      type: type,
      operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10',
      creditorName: this.data.searchValue || ""
    }

    let _this = this;
    request.requestGetMis_api("flyWorkPlace/customs", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("获取客户列表成功=", JSON.parse(res.data.body))
      let taskList = JSON.parse(res.data.body);
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (taskList.length > 0) {
        let tempList = _this.data.caseList;
        taskList.forEach(function (e) {
          e.txtStyle = "";
          e.img = e.grade == 3 ? 'stateA.png' : e.grade == 2 ? 'stateB.png' : (e.grade == 1) ? 'stateC.png' : 'state0.png';
        });
        for (var i = 0; i < taskList.length; i++) {
          tempList.push(taskList[i]);
        }
        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          searchNum: res.data.totalNum,
          totalPage: res.data.totalPage,
        });
      }
    }, (res) => {
      console.log("获取客户列表失败=", res)
    });
  },

  //获取律师协助
  getCounselCaseList: function (type, pageNum) {
    if (pageNum == 1) {
      this.setData({
        searchNum:0,
        caseList: new Array()
      });
    }
    let bodyInfo = {
      // type: type,
      // operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10',
      custName: this.data.searchValue || ""
    }
    let _this = this;
    console.log(bodyInfo)
    request.requestGetMis_api("lawyerAssist", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("获取协助律师列表成功=", JSON.parse(res.data.body))
      let taskList = JSON.parse(res.data.body);
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (taskList.length > 0) {
        let tempList = _this.data.caseList;
        taskList.forEach(function (e) {
          e.txtStyle = "";
          e.slt = "";
          e.img = e.grade == 3 ? 'stateA.png' : e.grade == 2 ? 'stateB.png' : (e.grade == 1) ? 'stateC.png' : 'state0.png';
          e.requestTime = util.timetrans(e.requestTime, 'day') + " " + util.timetrans(e.requestTime, 'time');
          e.talkTime = util.timetrans(e.talkTime, 'day') + " " + util.timetrans(e.talkTime, 'time')
          // e.caseAmt = util.filterFormatAmt(e.caseAmt * 1 / 10000);
          e.caseTypeDesc = e.caseType == '1' ? '诉讼案件' : e.caseType == '2' ? '执行案件' : '';
          e.assistModeDesc = e.assistMode == '1' ? '面谈' : e.assistMode == '2' ? '电话' : '';
        });
        for (var i = 0; i < taskList.length; i++) {
          tempList.push(taskList[i]);
        }
        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          searchNum: res.data.totalNum,
          totalPage: res.data.totalPage,
        });
      }
    }, (res) => {
      console.log("获取协助律师列表失败=", res)
    });
  },


  //****************************************顶部组件回调开始***************************************//
  //任务列表回调
  _goTaskPage: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    if (this.data.serachFlag) {
      this.setData({
        serachFlag: "",
        searchValue: ""
      });
    }
    this.setData({
      menuTab: menuTab,
      defaultDepart: departName,
      showCaseList: true,
      showStatusList: false,
      showShareDocList: false,
      show_client: false,
      searchNumStatus: false,//搜索结果显示与隐藏
    });
    this.getTaskCaseList(departName, 1)
  },

  //我的收藏
  _goCollectPage: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    if (this.data.serachFlag) {
      this.setData({
        serachFlag: "",
        searchValue: ""
      });
    }
    this.setData({
      menuTab: menuTab,
      defaultDepart: departName,
      showCaseList: true,
      showStatusList: false,
      showShareDocList: false,
    });
    this.getCollectCaseList(departName, 1)
  },

  //客户列表
  _goClientPage: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    if (this.data.serachFlag) {
      this.setData({
        serachFlag: "",
        searchValue: ""
      });
    }
    this.setData({
      menuTab: menuTab,
      defaultDepart: departName,
      showCaseList: true,
      showStatusList: false,
      showShareDocList: false,
      show_client: true,
      searchNumStatus: false,//搜索结果显示与隐藏
    });
    this.getClientCaseList(departName, 1)
  },

  //律师协助
  _golawyerHelpPage: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    if (this.data.serachFlag) {
      this.setData({
        serachFlag: "",
        searchValue: "",
      });
    }
    this.setData({
      menuTab: menuTab,
      defaultDepart: departName,
      showCaseList: false,
      showStatusList: true,
      showShareDocList: false,
      searchNumStatus: false,//搜索结果显示与隐藏
    });
    this.getCounselCaseList(departName, 1);
  },

  //文档库
  _goShareDoc: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    if (this.data.serachFlag) {
      this.setData({
        serachFlag: "",
        searchValue: ""
      });
    }
    this.setData({
      menuTab: menuTab,
      showCaseList: false,
      showStatusList: false,
      showShareDocList: true,
    });
    this.getCategoryList(0, "", 1);
  },

  //****************************************顶部组件回调结束***************************************//

  //****************************************滚动控制区域开始***************************************//
  //滚动到顶部
  upper: function (e) {
    console.log("顶部=", e)
  },
  addCust: function () {
    app.globalData.listRefresh.SuSong = {
      refresh: false
    }
    wx.navigateTo({
      url: '../addCust/addCust?isEdit=N',
    })
  },
  //滚动到底部
  lower: function (e) {
    console.log("底部=", e)
    let pageNum = this.data.pageNum;
    let totalPage = this.data.totalPage;
    // console.log("pageNum===", pageNum)
    // console.log("totalPage====", totalPage)
    if (pageNum < totalPage) {
      let typeTab = this.data.menuTab;
      if (typeTab == "task") {
        this.getTaskCaseList(this.data.defaultDepart, pageNum * 1 + 1)
      } else if (typeTab == "collect") {
        this.getCollectCaseList(this.data.defaultDepart, pageNum * 1 + 1);
      } else if (typeTab == "client") {
        this.getClientCaseList(this.data.defaultDepart, pageNum * 1 + 1)
      }
    } else {
      //显示没有更多字样
    }
  },

  //滚动到顶部
  upperXz: function (e) {
    console.log("顶部=", e)
  },

  //滚动到地底部
  lowerXz: function (e) {
    console.log("底部=", e)
    let pageNum = this.data.pageNum;
    let totalPage = this.data.totalPage;
    // console.log("pageNum===", pageNum)
    // console.log("totalPage====", totalPage)
    if (pageNum < totalPage) {
      this.getCounselCaseList(this.data.defaultDepart, pageNum * 1 + 1)
    } else {
      //显示没有更多字样
    }
  },


  //滚动到最新动态顶部
  upperStatus: function (e) {
    console.log("顶部=", e)
  },

  //****************************************滚动控制区域开始***************************************//

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.sstop = this.selectComponent("#ssTop");
  },

  //点击再次申请
  applyForAgain: function (e) {
    let info = e.currentTarget.dataset.info;
    app.globalData.custId = info.custId;
    app.globalData.listRefresh.SuSong = {
      refresh: false
    }
    wx.navigateTo({
      url: '../addCounsel/addCounsel?flag=second&caseAmt=' + info.caseAmt,
    })
  },


  //****************************************触发滑动收藏事件***************************************//
  collect: function (e) {
    let list = this.data.caseList;
    let info = e.currentTarget.dataset.info;
    let index = e.currentTarget.dataset.index;
    let _this = this;
    request.requestMisApi('post', "favorCusts/" + info.custId, { custId: info.custId }, (res) => {
      console.log("收藏成功=", res);
      list[index].isFavor = "Y";
      list[index].txtStyle = "";
      _this.setData({
        caseList: list
      });
      // wx.showToast({
      //   title: '收藏成功',
      //   icon: 'success',
      //   duration: 2000
      // })
      _this.getStatusNum(_this.data.defaultDepart, "gz")
    }, (res) => {
      wx.hideLoading()
      console.log("收藏失败=", res)
    });
  },
  uncollect: function (e) {
    let _this = this;
    let list = this.data.caseList;
    let info = e.currentTarget.dataset.info;
    let index = e.currentTarget.dataset.index;
    request.requestMisApi('delete', "favorCusts/" + info.custId, { custId: info.custId }, (res) => {
      console.log("取消收藏成功=", res);
      // if (_this.data.menuTab == "collect") {
      //   list.splice(index, 1);
      // } else {
      //   list[index].isFavor = "N";
      //   list[index].txtStyle = "";
      // }
      list[index].isFavor = "N";
      list[index].txtStyle = "";
      _this.setData({
        caseList: list
      });
      _this.getStatusNum(_this.data.defaultDepart, "gz")
    }, (res) => {
      wx.hideLoading()
      console.log("取消收藏失败=", res)
    });
  },
  touchS: function (e) {
    if (this.data.menuTab == 'collect' || this.data.menuTab == 'client' || this.data.menuTab == "task") {
      return
    }
    if (e.touches.length == 1) {
      // console.log("e.touches[0]===", e.touches[0])
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX,
        startY: e.touches[0].clientY,
      });
    }
  },

  touchM: function (e) {
    if (this.data.menuTab == 'collect' || this.data.menuTab == 'client' || this.data.menuTab == "task") {
      return
    }
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      let moveX = e.touches[0].clientX;
      let moveY = e.touches[0].clientY;
      // console.log("moveX===", e.touches[0])
      //手指起始点位置与移动期间的差值
      let disY = this.data.startY - moveY;
      let disX = this.data.startX - moveX;
      let delBtnWidth = this.data.delBtnWidth;
      let txtStyle = "";
      // if (Math.abs(disY*1) > 20){
      //   txtStyle = "left:0px";
      // }else{
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 100 && Math.abs(disY * 1) < 20) {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      // }

      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.caseList;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        caseList: list
      });
    }
  },

  touchE: function (e) {
    if (this.data.menuTab == 'collect' || this.data.menuTab == 'client' || this.data.menuTab == "task") {
      return
    }
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      let endX = e.changedTouches[0].clientX;
      let endY = e.changedTouches[0].clientY;
      //触摸开始与结束，手指移动的距离
      let disX = this.data.startX - endX;
      let disY = this.data.startY - endY;
      if (Math.abs(disY * 1) > 50) {//垂直滑动距离大于50则不触发
        return
      }
      let delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      let txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      let index = e.currentTarget.dataset.index;
      let list = this.data.caseList;
      if (txtStyle != "left:0px") {
        list.forEach(function (e) {
          e.txtStyle = "";
        });
      }

      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        caseList: list
      });
    }
  },

  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    let real = 0;
    try {
      let res = wx.getSystemInfoSync().windowWidth;
      let scale = (750 / 2) / (w / 2);//以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },

  //初始化宽度
  initEleWidth: function () {
    let delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },

  //****************************************触发滑动收藏事件结束***************************************//


  //去详情界面
  goDetInfo: function (e) {
    app.globalData.custId= e.currentTarget.dataset.custid;
    app.globalData.listRefresh.SuSong={
      refresh:false,
      custId: e.currentTarget.dataset.custid,
      itemIndex: e.currentTarget.dataset.index
    }
    wx.navigateTo({
      url: '../clientPro/clientPro',
    })
  },

  //显示律师协助的更多信息
  showDetInfo: function (e) {
    let list = this.data.caseList;
    // console.log("list====", list)
    let index = e.currentTarget.dataset.index;

    if (list[index].slt) {
      list[index].slt = false;
    } else {
      list.forEach(function (e) {
        e.slt = false;
      });
      list[index].slt = true;
    }
    this.setData({
      caseList: list
    })
  },

  //拨打电话
  callPhone: function (e) {
    let pho = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: pho
    })
  },


  //-----------文档库-----------
  getCategoryList: function (level, categoryId, pageNum) {
    wx.showLoading({
      title: '加载中...', mask: true
    })
    this.setData({
      folderList: [],
      level: level,
      isGetNextPage: true,
    })
    if (pageNum == 1) {
      this.setData({
        docList: [],
      });
    }
    if (level == 'none') {
      this.getDocList(categoryId, pageNum);
      return;
    }
    let bodyInfo = { level: level }
    if (categoryId && categoryId != 'none' && level != '0') {
      bodyInfo.parentId = categoryId;
    }
    console.log("shareCategorys", bodyInfo)
    let _this = this;
    request.requestMisApi("get", "shareCategorys", bodyInfo, (res) => {
      wx.hideLoading();
      if (res.code == '00') {
        console.log("获取文档目录成功=", JSON.parse(res.body))
        _this.setData({
          folderList: JSON.parse(res.body),
        });
        if (categoryId) {
          _this.getDocList(categoryId, pageNum);
        } else {
          _this.setData({
            docList: [],
            isGetNextPage: false,
          });
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取文档目录成功=", res)
    });
  },
  getDocList: function (categoryId, pageNum) {
    wx.showLoading({
      title: '加载中...', mask: true
    })
    let bodyInfo = {
      docFileName: this.data.searchValue || "",
      pageNum: pageNum,
      pageSize: '10'
    }
    if (categoryId != 'none') {
      bodyInfo.categoryId = categoryId
    }
    console.log("shareDocs", bodyInfo)
    let _this = this;
    request.requestMisApi("get", "shareDocs", bodyInfo, (res) => {
      wx.hideLoading();
      if (res.code == '00') {
        console.log("获取文档成功=", JSON.parse(res.body))
        let docList = this.data.docList;
        JSON.parse(res.body).forEach((item) => {
          item.sizeDesc = item.docSize * 1 < 1024 ? item.docSize + 'KB' : (item.docSize / 1024).toFixed(2) + 'MB';
          item.timeDesc = util.dateStr(item.uploadDate);
          if (/.doc$/.test(item.docFileName) || /.docx$/.test(item.docFileName)) {
            item.iconImg = 'file_word';
            item.canOpen = true;
          } else if (/.xls$/.test(item.docFileName) || /.xlsx$/.test(item.docFileName)) {
            item.iconImg = 'file_exl';
            item.canOpen = true;
          } else if (/.zip$/.test(item.docFileName)) {
            item.iconImg = 'file_zip'
          } else if (/.png$/.test(item.docFileName)) {
            item.iconImg = 'file_png';
            item.canOpen = true;
          } else if (/.exe$/.test(item.docFileName)) {
            item.iconImg = 'file_exe'
          } else if (/.gif$/.test(item.docFileName)) {
            item.iconImg = 'file_gif'
          } else if (/.jpg$/.test(item.docFileName) || /.jpeg$/.test(item.docFileName)) {
            item.iconImg = 'file_jpg';
            item.canOpen = true;
          } else if (/.ios$/.test(item.docFileName)) {
            item.iconImg = 'file_ios'
          } else if (/.pdf$/.test(item.docFileName)) {
            item.iconImg = 'file_pdf';
            item.canOpen = true;
          } else if (/.ppt$/.test(item.docFileName) || /.pptx$/.test(item.docFileName)) {
            item.iconImg = 'file_ppt';
            item.canOpen = true;
          } else if (/.txt$/.test(item.docFileName)) {
            item.iconImg = 'file_txt';
          } else {
            item.iconImg = 'file_other'
          }
          docList.push(item)
        })
        _this.setData({
          docList: docList,
          pageDocNum: pageNum,
          totalDocPage: res.totalPage
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
      _this.setData({
        isGetNextPage: false,
      });
    }, (res) => {
      _this.setData({
        isGetNextPage: false,
      });
      wx.hideLoading();
      console.log("获取文档成功=", res)
    });
  },
  folderClick: function (e) {
    console.log(e)
    let category = e.currentTarget.dataset.category;
    this.setData({ categoryId: this.data.categoryIdList.push(category.categoryId) })
    this.getCategoryList(category.level * 1 + 1, category.categoryId, 1)
  },
  folderBack: function () {
    if (this.data.level == 'none') {
      this.getCategoryList(0, this.data.categoryIdList[this.data.categoryIdList.length - 2], 1)
    } else {
      this.getCategoryList(this.data.level * 1 - 1, this.data.categoryIdList[this.data.categoryIdList.length - 2], 1)
    }
    this.setData({ categoryId: this.data.categoryIdList.pop() })
  },
  shareDocSearch: function () {
    this.setData({
      serachFlag: 1
    });
    if (this.data.searchValue) {
      this.setData({ categoryId: this.data.categoryIdList.push('none') })
      this.getCategoryList('none', 'none', 1)
    }
  },
  lowerShareDoc: function () {
    let pageDocNum = this.data.pageDocNum;
    let totalDocPage = this.data.totalDocPage;
    if (pageDocNum < totalDocPage && !this.data.isGetNextPage) {
      this.getCategoryList(this.data.level, this.data.categoryIdList[this.data.categoryIdList.length - 1], pageDocNum * 1 + 1)
    } else {
      //显示没有更多字样
    }
  },
  docClick(e) {
    let doc = e.currentTarget.dataset.doc
    if (doc.canOpen) {
      this.dowmloadFile(doc.docUrl, doc.docFileName)
    } else {
      wx.setClipboardData({
        data: doc.docUrl,
        success: function (res) {
          console.log(res)
          wx.showToast({
            title: '复制链接成功',
            icon: 'success',
            duration: 700
          })
          setTimeout(() => {
            wx.showModal({
              content: '该文件无法预览，文件路径已复制到剪切板，你可以打开浏览器下载',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }, 700)
        }
      })
    }
  },
  docLongpress: function (e) {
    let doc = e.currentTarget.dataset.doc
    wx.setClipboardData({
      data: doc.docUrl,
      success: function (res) {
        console.log(res)
        wx.showToast({
          title: '复制链接成功',
          icon: 'success',
          duration: 800
        })
      }
    })
  },
  //点击下载文件
  dowmloadFile: function (fileurl, docName) {
    let _this = this;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl, docName)
    wx.showLoading({ title: ' ', mask: true })
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        wx.hideLoading()
        _this.setData({ isFromOpenDoc: true })
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        console.log("读取文件失败=", res);
      }
    })
  },
  //转发
  // onShareAppMessage: function(res){

  // }
})
